<?php
/**
 *  * author 韩天尊
 * Date: 2022/3/24
 * Email: <724700483@qq.com>
 */

namespace App\Toolys;

/**
 * 单纯事件锁：比如验证码获取 1分钟后才能再次获取 ：
 *
 *  事件锁
 */
class ApiEventLock
{
    public string $eventValue;//值
    public string $eventName;//触发主事件名
    public array $associations;//关联事件名

    public int $trialFrequency;//事件可试错次数

    public function __construct(string $eventValue, string $eventName, int $trialFrequency=3, array $associations=[])
    {
        $this->eventValue = $eventValue;
        $this->eventName = $eventName;
        $this->trialFrequency = $trialFrequency;
        $this->associations = $associations;
    }

    public function __set($name, $value)
    {
        // TODO: Implement __set() method.
        $this->{$name} = $value;
        return $this;
    }
    public function __get($name)
    {
        // TODO: Implement __get() method.
        return $this->{$name};
    }

    /**
     * @param int $time
     * @param array $data => []
     * @return mixed|null
     * @throws \EasySwoole\Redis\Exception\RedisException
     * @author 韩天尊
     * @date 2022-03-24 15:24
     */
    public function lock(int $time=60, array $data=[])
    {
        $key = "{$this->eventName}-{$this->eventValue}";
        return _sealRedis(function (\EasySwoole\Redis\Redis $redis) use($key,$time,$data){
            $redis->set($key, json_encode($data), $time);
        });
    }


    public function getLockData()
    {
        $key = "{$this->eventName}-{$this->eventValue}";
        return _sealRedis(function (\EasySwoole\Redis\Redis $redis) use($key){
              json_decode($redis->get($key));
        });
    }


    /** 查询剩余时间
     * @return mixed|null
     * @author 韩天尊
     * @date 2022-03-24 10:11
     */
    public function lockTtl()
    {
        return _sealRedis(function (\EasySwoole\Redis\Redis $redis){
            $ttl = $redis->ttl("{$this->eventName}-{$this->eventValue}");
            if (($ttl==-2) || ($ttl==-1)){//-2 key不存在 -1 值永不过期
                $ttl = 0;
            }
            return $ttl;
        });
    }
}